# 处理菜单
import re
import requests
from processing.Sql_DataFrom import ProJosn
def menuChuli(i):
    if i['menuType'] == 1:
        menuType = 'MENU'
    else:
        menuType = 'BUTTON'

    if i['showLink'] == 1:
        showLink = True
    else:
        showLink = False
    if i['status'] == 'normal' or i['status'] == True:
        show = True
    else:
        show = False
    i['code'] = i['auths']
    i['type'] = menuType
    i['order'] = i['menuRank']
    i['enable'] = showLink
    i['show'] = show
    i['layout'] = i['frameLoading']
    return i

def menuListChuli(menuList,db):
    munuData = []
    if len(menuList) > 0:

        for i in menuList:

            if i['parentId'] == 0:
                # 添加一级
                munuData.append(menuChuli(i))
                munuData_children = []
                for j in menuList:
                    if j['parentId'] == 0:
                        continue
                    else:
                        # 处理二级菜单

                        if j['parentId'] == munuData[len(munuData)-1]['id']:

                            sql_find_children = f"""
                                    select id,frameLoading,redirect,keepAlive,menuType,name,icon,component,menuRank,parentId,path,auths,showLink,ctime,status from authority_menus where id=%s ORDER BY menuRank ASC
                                """
                            menuList_children = db.find_all(sql_find_children, (j['id']))
                            menuList_children = ProJosn(menuList_children, sql_find_children)

                            # # 判断是否有子菜单
                            if len(menuList_children) > 0:

                                for i_children in menuList_children:
                                    munuData_children.append(menuChuli(i_children))

                                #     if i_children['menuType'] == 2:
                                # #         # 判断是否有按钮权限
                                #         sql_find_children_botton = f"""
                                #                 select id,frameLoading,redirect,keepAlive,menuType,name,icon,component,menuRank,parentId,path,auths,showLink,ctime,status from authority_menus where parentId=%s and menuType=2 ORDER BY menuRank ASC
                                #             """
                                #         menuList_children_button = db.find_all(sql_find_children_botton, (i_children['id']))
                                #
                                #         menuList_children_button = ProJosn(menuList_children_button,
                                #                                            sql_find_children_botton)
                                #
                                #         if len(menuList_children_button) > 0:
                                #
                                #             munuData_children_button = []
                                #             for i_children_button in menuList_children_button:
                                #                 munuData_children_button.append(menuChuli(i_children_button))
                                #                 munuData_children[len(munuData_children) - 1][
                                #                     'children'] = munuData_children_button
                            munuData[len(munuData) - 1]['children'] = munuData_children
    # print(munuData)
    return munuData

# def menuListChuli(menuList,db):
#     munuData = []
#     if len(menuList) > 0:
#
#         for i in menuList:
#
#             if i['parentId'] == 0:
#                 munuData.append(menuChuli(i))
#
#                 # 处理二级菜单
#                 sql_find_children = f"""
#                     select id,frameLoading,redirect,keepAlive,menuType,name,icon,component,menuRank,parentId,path,auths,showLink,ctime,status from authority_menus where parentId=%s ORDER BY menuRank ASC
#                 """
#                 menuList_children = db.find_all(sql_find_children, (i['id']))
#                 menuList_children = ProJosn(menuList_children, sql_find_children)
#                 # 判断是否有子菜单
#                 if len(menuList_children) > 0:
#                     munuData_children = []
#                     for i_children in menuList_children:
#                         munuData_children.append(menuChuli(i_children))
#                         # 获取当前数组下标
#
#                         # 判断是否有按钮权限
#                         sql_find_children_botton = f"""
#                                 select id,frameLoading,redirect,keepAlive,menuType,name,icon,component,menuRank,parentId,path,auths,showLink,ctime,status from authority_menus where parentId=%s and menuType=2 ORDER BY menuRank ASC
#                             """
#                         menuList_children_button = db.find_all(sql_find_children_botton, (i_children['id']))
#
#                         menuList_children_button = ProJosn(menuList_children_button, sql_find_children_botton)
#
#                         if len(menuList_children_button) > 0:
#
#                             munuData_children_button = []
#                             for i_children_button in menuList_children_button:
#                                 munuData_children_button.append(menuChuli(i_children_button))
#                                 munuData_children[len(munuData_children) - 1]['children'] = munuData_children_button
#                     munuData[len(munuData) - 1]['children'] = munuData_children
#
#     return munuData

def fenpeiRole(userid,db,html_data):
    # 分配角色
    find_sql_role = """
            select id,user_id,role_id from ausers_roles where user_id=%s
        """

    roleList = db.find_all(find_sql_role, userid)
    if roleList:

        role_sql = """
                    update ausers_roles set role_id=%s,ctime=now() where user_id=%s
                """
        if 'roleIds' in list(html_data):  # 判断是否分配角色了
            role_str = ''
            for i in range(0, len(html_data['roleIds'])):
                if i == 0:
                    role_str += str(html_data['roleIds'][i])
                else:
                    role_str += ',' + str(html_data['roleIds'][i])

            db.update(role_sql, (role_str, userid))

    else:
        # print(12321,html_data['roleIds'])
        if 'roleIds' in list(html_data):  # 判断是否分配角色了
            role_str = ''

            for i in range(0, len(html_data['roleIds'])):
                if i == 0:
                    role_str += str(html_data['roleIds'][i])
                else:
                    role_str += ',' + str(html_data['roleIds'][i])
            sql_add_role = "insert into ausers_roles(user_id,role_id,ctime ) VALUES (%s,%s,now())"

            db.insert(sql_add_role, (userid, role_str))
    return True


# 排序
def sqlOrder(sql,type='ctime',way='DESC'):
    sql += f" ORDER BY {type} {way} "
    return sql

def sqlPaging(pageNum,pageSize,sql):

    # 分页pageNum
    if pageNum == 1:
        sql += f" LIMIT {pageSize} "
    else:
        sql += f" LIMIT {pageNum * pageSize - pageSize},{pageSize} "

    return sql

def sqlKeyword(keyword,sql,tol,list=[],where=''):
    if keyword:
        sql += f" {where} or "


        # tol += f" where  nickName LIKE '%{keyword}%' or account LIKE '%{keyword}%' or phone LIKE '%{keyword}%'"
        for i in range(0,len(list)):
            if i == 0:
                sql += f" {list[i]} LIKE '%{keyword}%' "
            else:
                sql += f" or {list[i]} LIKE '%{keyword}%' "


        # sql += f" where  nickName LIKE '%{keyword}%' or  account LIKE '%{keyword}%' or  phone LIKE '%{keyword}%'"
        # tol += f" where  nickName LIKE '%{keyword}%' or account LIKE '%{keyword}%' or phone LIKE '%{keyword}%'"
    return str(sql).replace('\n',''),tol

def set_status(item):
    if item == 1 or item == '1' or item == True or item == 'True' or item == 'true':
        return 'normal'
    else:
        return 'destroy'
def set_status_None(item):
    if item == None or item == 'None':
        return ''
    else:
        return item
def set_status_number(item):
    try:
        if item == 1 or item == '1' or item == True or item == 'True' or item == 'true':
            return 1
        else:
            return 0
    except Exception as error:
        if item == 1 or item == '1' or item == True or item == 'True' or item == 'true':
            return '1'
        else:
            return '0'


import time


def timestamp_to_standard(timestamp):

    if timestamp > 173512315000:
        standard_time = time.gmtime(int(timestamp) / 1000)
    else:
        standard_time = time.gmtime(int(timestamp))
    return time.strftime("%Y-%m-%d %H:%M:%S", standard_time)

def AI_Spark_desk(content='',max_tokens=100,top_k=4,temperature=0.5,stream=True):
        url = "https://spark-api-open.xf-yun.com/v1/chat/completions"
        data = {
            "max_tokens": max_tokens, # 文字的最大长度 8192
            "top_k": top_k,  #  灵活度 1~6
            "temperature": temperature, # 随机性  0.1~1
            "messages": [
                {
                    "role": "system",
                    "content": ""
                },
                {
                    "role": "user",
                    "content": content
                }
            ],
            "model": "4.0Ultra"
        }
        data["stream"] = stream  # 搜索溯源 该参数仅4.0 Ultra版本支持，当设置为true时，如果输入内容触发联网检索插件，会先返回检索信源列表，然后再返回星火回复结果，否则仅返回星火回复结果
        header = {
            "Authorization": "Bearer HpmQUXUOksnrfJfCLRsI:SZWqsJECzJRTljEWioaN"
        }
        print(url)
        response = requests.post(url, headers=header, json=data, stream=True)

        # 流式响应解析示例
        response.encoding = "utf-8"
        desk_data = []
        for line in response.iter_lines(decode_unicode="utf-8"):
            re_str = r'\[(.*?)\]'
            result = str(re.findall(re_str,line)).replace('[','').replace(']','').replace("'",'').replace("'",'').replace("'",'').replace("'",'')
            if len(result):
                if result == "DONE":
                    pass
                else:
                    print(eval(result)['delta'])
                    desk_data.append(eval(result)['delta'])
        return desk_data,data


def setTime(Time):
    if Time:
        Times = timestamp_to_standard(Time)

    else:
        Times = '2024-01-01 08:00:00'

    return Times

def order_log(db,data):
    try:

        sql = f"""
            insert into order_log(merchant_id,order_id,order_log,content,goods_info,user_info,type,payStatus,openid,order_info,ctime) values (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
        """
        db.insert(sql,(
            data['merchant_id'],
            data['order_id'],
            data['order_log'],
            data['content'],
            data['goods_info'],
            data['user_info'],
            data['type'],
            data['payStatus'],
            data['openid'],
            data['order_info'],
        ))
        return 200
    except Exception as error:
        return 500
